<template>
	<view class="kaoqin-page">
	<view class="calendar-container">
		<!-- 年月选择器 -->
		<view class="month-selector">
			<view class="selector-box">
				<picker mode="date" fields="month" :value="currentDate" @change="onDateChange">
					<view class="picker-content">
						<text>{{ yearMonth }}</text>
						<uni-icons type="bottom" size="14" color="#666"></uni-icons>
					</view>
				</picker>
			</view>
		</view>

		<!-- 日历网格 -->
		<view class="calendar-grid">
			<!-- 星期标题 -->
			<view class="week-header">
				<view class="week-item" v-for="(week, index) in weekDays" :key="index">{{ week }}</view>
			</view>
			
			<!-- 日期网格 -->
			<view class="days-grid">
				<view 
					class="day-item" 
					v-for="(day, index) in daysInMonth" 
					:key="index"
					:class="{ 
						'empty': !day,
						'attended': day && isAttended(day),
						'abnormal-attendance': day && isAbnormalAttendance(day)
					}"
				>
					<view class="day-content" v-if="day">
						<text class="day-number">{{ day }}</text>
						<text v-if="isAttended(day)" class="attendance-text">已出勤</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading">加载中...</view>
		</view>

		<!-- 晚到拍照功能 -->
		<view class="late-photo-section">
			<view class="section-title">晚到拍照记录</view>
			
			<!-- 照片上传部分 -->
			<view class="photo-section">
				<view class="photo-preview" v-if="photoUrl">
					<image :src="photoUrl" mode="widthFix" @click="previewImage" class="preview-image"></image>
					<view class="photo-actions">
						<button class="delete-btn" @click="deletePhoto">X</button>
					</view>
				</view>
				<view v-else class="photo-upload">
					<button class="upload-btn" @click="takePhoto">
						<text class="upload-icon">📷</text>
						<text>拍照</text>
					</button>
				</view>
				<button class="submit-btn" 
					:disabled="!photoUrl || isSubmittingPhoto" 
					@click="handleSubmitPhoto"
					:class="{ 'submit-btn-disabled': !photoUrl || isSubmittingPhoto }">
					<view v-if="isSubmittingPhoto" class="loading-spinner"></view>
					<text>{{ isSubmittingPhoto ? '提交中...' : '提交照片' }}</text>
				</button>
			</view>

			<!-- 问题反馈部分 -->
			<view class="problem-section">
				<textarea 
					v-model="problemDescription" 
					placeholder="请输入晚到原因描述"
					class="problem-textarea"
					:maxlength="500"
					show-confirm-bar="false"
				/>
				<button class="submit-btn" 
					:disabled="!problemDescription || isSubmittingProblem" 
					@click="handleSubmitProblem"
					:class="{ 'submit-btn-disabled': !problemDescription || isSubmittingProblem }">
					<view v-if="isSubmittingProblem" class="loading-spinner"></view>
					<text>{{ isSubmittingProblem ? '提交中...' : '提交说明' }}</text>
				</button>
			</view>

			<!-- 晚到拍照记录展示区域 -->
			<view class="feedback-records">
				<view class="records-title">晚到拍照记录</view>
				<view class="records-grid">
					<view v-for="(record, index) in feedbackRecords" :key="index" class="record-item">
						<image :src="record.photoUrl" mode="aspectFill" @click="previewRecordImage(record.photoUrl)" class="record-image"></image>
						<view class="record-info">
							<text class="record-user">{{ record.userName }}</text>
							<text class="record-time">{{ formatDate(record.photoTime) }}</text>
							<text class="record-description">{{ record.description || '无说明' }}</text>
						</view>
					</view>
				</view>
				<view v-if="feedbackRecords.length === 0" class="no-records">暂无晚到拍照记录</view>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '@/config'
	import { listAttendance } from '@/api/system/attendance'
	import { uploadLatePhoto, submitLateFeedback, listLate } from '@/api/system/photo'
	import { getToken } from '@/utils/auth'
	
	export default {
		data() {
			const now = new Date()
			const year = now.getFullYear()
			const month = String(now.getMonth() + 1).padStart(2, '0')
			return {
				currentDate: `${year}-${month}`, // 默认当前年月
				weekDays: ['日', '一', '二', '三', '四', '五', '六'],
				attendedDays: [], // 存储已出勤的日期
				loading: false, // 加载状态
				attendanceList: [], // 存储考勤数据
				photoUrl: '', // 拍照后的图片URL
				problemDescription: '', // 问题描述
				feedbackRecords: [], // 存储反馈记录
				isSubmittingPhoto: false, // 是否正在提交照片
				isSubmittingProblem: false // 是否正在提交问题
			}
		},
		computed: {
			yearMonth() {
				const [year, month] = this.currentDate.split('-')
				return `${year}年${month}月`
			},
			daysInMonth() {
				const [year, month] = this.currentDate.split('-')
				const date = new Date(year, month, 0)
				const daysCount = date.getDate()
				const firstDay = new Date(year, month - 1, 1).getDay()
				
				// 创建日期数组，前面补充空值
				const days = Array(firstDay).fill(null)
				for (let i = 1; i <= daysCount; i++) {
					days.push(i)
				}
				
				// 确保总长度是7的倍数
				while (days.length % 7 !== 0) {
					days.push(null)
				}
				
				return days
			},
			// 新增：判断当前用户是否为业务员
			isSalesperson() {
				const roles = uni.getStorageSync('roles')
				return roles && roles.includes('yewuyuan')
			}
		},
		methods: {
			// 获取考勤数据
			async getAttendanceData() {
				this.loading = true
				try {
					const userInfo = uni.getStorageSync('userInfo')
					if (!userInfo || !userInfo.user) {
						throw new Error('未获取到用户信息')
					}

					const [year, month] = this.currentDate.split('-')
					const startDate = `${year}-${month}-01`
					const endDate = `${year}-${month}-${new Date(year, month, 0).getDate()}`

					const res = await listAttendance({
						userId: userInfo.user.userId,
						startDate: startDate,
						endDate: endDate
					})

					if (res.code === 200) {
						this.attendanceList = res.rows || []
						this.updateAttendedDays()
					} else {
						this.$modal.msgError(res.msg || '获取考勤数据失败')
					}
				} catch (error) {
					console.error('获取考勤数据失败:', error)
					this.$modal.msgError('获取考勤数据失败')
				} finally {
					this.loading = false
				}
			},

			// 更新已出勤日期
			updateAttendedDays() {
				this.attendedDays = this.attendanceList.map(item => {
					const date = new Date(item.punchDate)
					return date.getDate()
				})
			},

			// 日期选择改变
			async onDateChange(e) {
				this.currentDate = e.detail.value
				await this.getAttendanceData()
			},

			// 检查日期是否已出勤
			isAttended(day) {
				return this.attendedDays.includes(day)
			},

			// 拍照
			takePhoto() {
				uni.chooseImage({
					count: 1,
					sourceType: ['camera'],
					sizeType: ['compressed'], // 使用系统自带的压缩选项
					success: (res) => {
						this.photoUrl = res.tempFilePaths[0]
					},
					fail: (err) => {
						console.error('拍照失败:', err)
						this.$modal.msgError('拍照失败')
					}
				})
			},
			
			// 预览图片
			previewImage() {
				uni.previewImage({
					urls: [this.photoUrl],
					current: this.photoUrl
				})
			},
			
			// 删除照片
			deletePhoto() {
				this.photoUrl = ''
			},
			
			// 处理提交照片
			async handleSubmitPhoto() {
				if (!this.photoUrl) {
					this.$modal.msgError('请先拍照')
					return
				}
				
				this.isSubmittingPhoto = true
				
				try {
					// 获取当前用户信息
					const userInfo = uni.getStorageSync('userInfo')
					if (!userInfo || !userInfo.user || !userInfo.user.userId || !userInfo.user.userName) {
						throw new Error('未获取到用户信息，请重新登录')
					}
					
					// 使用uni.uploadFile上传图片
					const uploadRes = await new Promise((resolve, reject) => {
						uni.uploadFile({
							url: config.baseUrl + '/system/photo/uploadLatePhoto',
							filePath: this.photoUrl,
							name: 'file',
							header: {
								'Authorization': 'Bearer ' + getToken()
							},
							success: (res) => {
								try {
									const data = JSON.parse(res.data)
									resolve(data)
								} catch (error) {
									reject(new Error('解析响应失败'))
								}
							},
							fail: (err) => {
								reject(new Error(err.errMsg || '上传失败'))
							}
						})
					})
					
					if (uploadRes.code !== 200 || !uploadRes.data) {
						throw new Error(uploadRes.msg || '图片上传失败')
					}
					
					// 格式化日期
					const now = new Date()
					const formattedDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
					
					// 构建反馈数据
					const feedbackData = {
						userId: userInfo.user.userId,
						userName: userInfo.user.userName,
						photoUrl: uploadRes.data,
						photoTime: formattedDate,
						description: this.problemDescription || '晚到拍照记录' // 照片提交时包含问题描述
					}
					
					const res = await submitLateFeedback(feedbackData)
					if (res.code === 200) {
						this.$modal.msgSuccess('晚到拍照记录提交成功')
						this.photoUrl = '' // 清空照片
						this.problemDescription = '' // 清空问题描述
						this.getLatePhotoRecords() // 刷新反馈记录
					} else {
						throw new Error(res.msg || '晚到拍照记录提交失败')
					}
				} catch (error) {
					console.error('晚到拍照记录提交失败:', error)
					this.$modal.msgError(error.message || '晚到拍照记录提交失败')
				} finally {
					this.isSubmittingPhoto = false
				}
			},

			// 处理提交问题
			async handleSubmitProblem() {
				if (!this.problemDescription.trim()) {
					this.$modal.msgError('请输入晚到原因描述')
					return
				}
				
				this.isSubmittingProblem = true
				
				try {
					// 获取当前用户信息
					const userInfo = uni.getStorageSync('userInfo')
					if (!userInfo || !userInfo.user || !userInfo.user.userId || !userInfo.user.userName) {
						throw new Error('未获取到用户信息，请重新登录')
					}
					
					// 格式化日期
					const now = new Date()
					const formattedDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
					
					// 构建反馈数据
					const feedbackData = {
						userId: userInfo.user.userId,
						userName: userInfo.user.userName,
						photoUrl: '', // 问题提交时不包含照片
						photoTime: formattedDate,
						description: this.problemDescription
					}
					
					const res = await submitLateFeedback(feedbackData)
					if (res.code === 200) {
						this.$modal.msgSuccess('晚到说明提交成功')
						this.problemDescription = '' // 清空问题描述
						this.getLatePhotoRecords() // 刷新反馈记录
					} else {
						throw new Error(res.msg || '晚到说明提交失败')
					}
				} catch (error) {
					console.error('晚到说明提交失败:', error)
					this.$modal.msgError(error.message || '晚到说明提交失败')
				} finally {
					this.isSubmittingProblem = false
				}
			},

			// 获取晚到拍照记录
			async getLatePhotoRecords() {
				try {
					const userInfo = uni.getStorageSync('userInfo')
					if (!userInfo || !userInfo.user || !userInfo.user.userId) {
						throw new Error('未获取到用户信息')
					}

					const query = {
						pageNum: 1,
						pageSize: 50,
						userId: userInfo.user.userId
					}

					const res = await listLate(query)
					if (res.code === 200) {
						this.feedbackRecords = res.rows || []
					} else {
						console.error('获取晚到拍照记录失败:', res.msg)
					}
				} catch (error) {
					console.error('获取晚到拍照记录失败:', error)
				}
			},

			// 预览记录中的图片
			previewRecordImage(url) {
				uni.previewImage({
					urls: [url],
					current: url
				})
			},

			// 格式化日期
			formatDate(timestamp) {
				if (!timestamp) return ''
				const date = new Date(timestamp)
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
			},

			// 新增：判断业务员当天考勤是否异常
			isAbnormalAttendance(day) {
				if (!this.isSalesperson) return false;
				const record = this.attendanceList.find(item => {
					return item.punchDate && new Date(item.punchDate).getDate() === day;
				});
				// aa不是"业务员打卡并上班"即为异常
				return record && record.aa !== '业务员打卡并上班';
			}
		},
		onLoad() {
			this.getAttendanceData()
			this.getLatePhotoRecords()
		}
	}
</script>

<style lang="scss" scoped>
.kaoqin-page {
	background-color: #f5f7fa;
	min-height: 100vh;
}

.calendar-container {
	padding: 20rpx;
	background-color: #f5f7fa;
}

.month-selector {
	margin-bottom: 30rpx;
	
	.selector-box {
		background: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
		
		.picker-content {
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32rpx;
			color: #333;
			
			text {
				margin-right: 10rpx;
			}
		}
	}
}

.calendar-grid {
	background: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	
	.week-header {
		display: grid;
		grid-template-columns: repeat(7, 1fr);
		margin-bottom: 20rpx;
		
		.week-item {
			text-align: center;
			font-size: 28rpx;
			color: #909399;
			padding: 10rpx 0;
		}
	}
	
	.days-grid {
		display: grid;
		grid-template-columns: repeat(7, 1fr);
		gap: 10rpx;
		
		.day-item {
			aspect-ratio: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			background: #f5f7fa;
			border-radius: 8rpx;
			font-size: 28rpx;
			color: #333;
			position: relative;
			
			&.empty {
				background: transparent;
			}
			
			&.attended {
				background: #409EFF;
				color: #fff;
				
				.attendance-text {
					color: #fff;
				}
			}
			
			&:active {
				background: #e6f7ff;
				
				&.attended {
					background: #66b1ff;
				}
			}
			
			.day-content {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				
				.day-number {
					font-size: 32rpx;
					font-weight: bold;
					margin-bottom: 4rpx;
				}
				
				.attendance-text {
					font-size: 20rpx;
					color: #fac221;
				}
			}
		}
	}
}

.loading {
	text-align: center;
	padding: 30rpx;
	color: #999;
	font-size: 28rpx;
}

.late-photo-section {
	margin-top: 30rpx;
	padding: 20rpx;
	background-color: #fff;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}
	
	.photo-section {
		margin-bottom: 20rpx;
		
		.photo-preview {
			position: relative;
			margin-bottom: 10rpx;
			
			.preview-image {
				width: 100%;
				height: 200rpx;
				border-radius: 8rpx;
			}
			
			.photo-actions {
				position: absolute;
				top: 0;
				right: 0;
				padding: 10rpx;
				
				.delete-btn {
					background: rgba(0,0,0,0.5);
					color: #fff;
					border: none;
					border-radius: 50%;
					width: 32rpx;
					height: 32rpx;
					padding: 0;
					font-size: 20rpx;
					cursor: pointer;
				}
			}
		}
		
		.photo-upload {
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 20rpx;
			background: #f5f7fa;
			border-radius: 8rpx;
			
			.upload-btn {
				background: #409EFF;
				color: #fff;
				border: none;
				border-radius: 8rpx;
				padding: 10rpx 20rpx;
				font-size: 28rpx;
				cursor: pointer;
				
				.upload-icon {
					margin-right: 10rpx;
				}
			}
		}
		
		.submit-btn {
			margin-top: 20rpx;
			background: #409EFF;
			color: #fff;
			border: none;
			border-radius: 8rpx;
			padding: 10rpx 20rpx;
			font-size: 28rpx;
			cursor: pointer;
			
			&.submit-btn-disabled {
				background: #909399;
				cursor: not-allowed;
			}
		}
	}
	
	.problem-section {
		margin-bottom: 20rpx;
		
		.problem-textarea {
			width: 100%;
			height: 120rpx;
			border: 1rpx solid #909399;
			border-radius: 8rpx;
			padding: 10rpx;
			font-size: 28rpx;
		}
		
		.submit-btn {
			margin-top: 20rpx;
			background: #409EFF;
			color: #fff;
			border: none;
			border-radius: 8rpx;
			padding: 10rpx 20rpx;
			font-size: 28rpx;
			cursor: pointer;
			
			&.submit-btn-disabled {
				background: #909399;
				cursor: not-allowed;
			}
		}
	}
	
	.feedback-records {
		margin-top: 20rpx;
		
		.records-title {
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 20rpx;
		}
		
		.records-grid {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			gap: 10rpx;
			
			.record-item {
				display: flex;
				align-items: center;
				background: #f5f7fa;
				border-radius: 8rpx;
				padding: 10rpx;
				
				.record-image {
					width: 100%;
					height: 120rpx;
					border-radius: 8rpx;
					margin-right: 10rpx;
				}
				
				.record-info {
					flex: 1;
					
					.record-user {
						font-size: 28rpx;
						font-weight: bold;
						margin-bottom: 4rpx;
					}
					
					.record-time {
						font-size: 24rpx;
						color: #909399;
					}
					
					.record-description {
						font-size: 24rpx;
						color: #333;
					}
				}
			}
		}
		
		.no-records {
			text-align: center;
			padding: 20rpx;
			color: #909399;
		}
	}
}

.loading-spinner {
	display: inline-block;
	width: 20rpx;
	height: 20rpx;
	border: 2rpx solid #fff;
	border-radius: 50%;
	border-top-color: transparent;
	animation: spin 1s linear infinite;
	margin-right: 10rpx;
}

@keyframes spin {
	to {
		transform: rotate(360deg);
	}
}

.day-item.abnormal-attendance {
	background: #ff4d4f !important;
	color: #fff;
	border-radius: 8rpx;
}
</style>
